<script setup lang="ts">
import {Group, Object3D, Vector2} from 'three'
import { useTresContext } from "@tresjs/core";
import { TransformControls, useGLTF } from '@tresjs/cientos'
import { ShallowRef } from 'vue'
import {useEmitt} from "@/hooks/web/useEmitt";
import {useLoaderStorage} from "@/store/modules/web3d/loader";
import {ThemeVO} from "@/api/pb/theme";

const emitt = useEmitt()

const loader = useLoaderStorage()

const { camera, raycaster, renderer  } = useTresContext()

const theme = inject<Ref<ThemeVO>>('theme')!
const contentGroup = inject<Group>('contentGroup')!

/**
 * 编辑对象
 */
// 当前编辑对象
const editObject = inject<ShallowRef<Object3D | null>>('editObject')!
// 当前编辑模式
const editMode = inject<Ref<string>>('editMode')!

const handleClick = ({ object }: { object: Object3D}) => {
  editObject.value = object
  emitt.emit('clickModel', object.uuid)
}

// 是否正在操作控制器
const controlling = inject<Ref<boolean>>('controlling')!
// 是否正在编辑
const editing = ref(false)
const setEditing = (value: boolean) => {
  setTimeout(() => {
    editing.value = value
  }, 100)
}
renderer.value.domElement.addEventListener('click', (event: MouseEvent) => {
  if (controlling.value || editing.value) return

  const rect = renderer.value.domElement.getBoundingClientRect()
  const mouse = new Vector2()
  mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
  mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1

  raycaster.value.setFromCamera(mouse, camera.value!)

  const isEditObject = raycaster.value.intersectObjects(contentGroup.children).length > 0

  if (!isEditObject) {
    editObject.value = null
  }
})

</script>

<template>
  <primitive :object="contentGroup" @click="handleClick" />

  <TransformControls
    v-if="editObject"
    :object="editObject"
    :mode="editMode"
    @dragging="setEditing"
  />
</template>

<style scoped lang="scss"></style>
